<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <div class="card-header">
          <span>用户登录</span>
        </div>
      </template>
      <el-form :model="form" label-width="80px">
        <el-form-item label="学号">
          <el-input v-model="form.username" placeholder="请输入学号（默认123456）"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="form.pwd" type="password" placeholder="请输入密码（默认123456）"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">登录</el-button>
          <el-button @click="goToRegister">注册</el-button>
        </el-form-item>
        <div class="login-tip">
          <p>示例账号:23002944(学号),密码:123456</p>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'
import { userAPI } from '../api'
import { useRouter } from 'vue-router'

export default {
  name: 'LoginView',
  setup() {
    const router = useRouter()
    
    return {
      router
    }
  },
  data() {
    return {
      form: {
        username: '23002944', // 默认学号
        pwd: '123456',       // 默认密码
      }
    }
  },
  methods: {
    onSubmit() {
      if (!this.form.username || !this.form.pwd) {
        ElMessage.error('请输入用户名和密码')
        return
      }
      
      console.log('开始登录请求:', this.form)
      
      // 使用修复后的userAPI.login方法
      userAPI.login({
        username: this.form.username,
        pwd: this.form.pwd
      })
      .then(data => {
        console.log('登录API响应数据:', data)
        
        // 处理登录成功逻辑
        if (data && data.errno === 0) {
          // 从后端响应中获取真实的用户信息和token
          const userData = data.data
          
          // 存储真实的token和用户信息到localStorage
          localStorage.setItem('token', userData.token)
          localStorage.setItem('userInfo', JSON.stringify({
            id: userData.id,
            username: userData.username
          }))
          
          ElMessage.success('登录成功')
          
          // 触发登录成功事件，通知Header组件更新状态
          window.dispatchEvent(new CustomEvent('userLoggedIn'))
          
          this.$router.push('/')
        } else {
          // 登录失败
          ElMessage.error(data?.message || '登录失败，请检查用户名和密码')
        }
      })
      .catch(error => {
        console.error('登录失败', error)
        ElMessage.error('登录失败，请稍后重试')
      })
    },
    
    goToRegister() {
      this.$router.push('/register')
    }
  }
}</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}
.login-card {
  width: 400px;
}
.card-header {
  text-align: center;
  font-size: 20px;
}
.login-tip {
  margin-top: 15px;
  font-size: 14px;
  color: #606266;
}
</style>